from lufflyapi.utils.response import APIResponse

from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from django.core.cache import cache
from django.conf import settings

from . import models
from . import serializers


class BannerView(GenericViewSet, ListModelMixin):

    queryset = models.Banner.objects.filter(is_delete=False, is_show=True).order_by('-orders')
    serializer_class = serializers.BannerModelSerializer

    if not settings.BANNER_COUNT > len(queryset):
        queryset = queryset[:settings.BANNER_COUNT]

    def list(self, request, *args, **kwargs):
        pk = kwargs.get('pk', None)
        if pk:
            self.queryset = self.queryset.filter(pk=pk)
        # 1. 先去缓存获取数据，
        banner_data = cache.get(settings.BANNER_CACHE_KEY)
        if not banner_data:
            # 缓存中没有值，去数据库获取值
            response = super(BannerView, self).list(request, *args, **kwargs)
            cache.set(settings.BANNER_CACHE_KEY, response.data, 60*60*24*7)  # 缓存七天
            return APIResponse(result=response.data)

        return APIResponse(result=banner_data)
